package cn.objectspace.filessh.interceptor;

import cn.objectspace.util.Result;
import cn.objectspace.util.SshCodeMsg;
import cn.objectspace.util.TokenGenerator;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author pc
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public TokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头或请求参数中获取token值
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            token = request.getParameter("token");
        }

        if (token == null || token.isEmpty()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());

            // 设置响应内容的类型和编码
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
//            // 转换为JSON字符串
//            String s = JSONUtils.toJSONString(Result.error(SshCodeMsg.LOGIN_TIMEOUT));
            // 返回JSON字符串给前端
            writer.write("登录失效");
            writer.flush();
            return false;
        }
        System.out.println(token);

        if (!redisTemplate.hasKey(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            // 设置响应内容的类型和编码
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            // 转换为JSON字符串
            String s = JSONUtils.toJSONString("登录失效");
            // 返回JSON字符串给前端
            writer.write(s);
            writer.flush();
            return false;
        }
        //重新设置过期时间
        String userId = redisTemplate.opsForValue().get(token);
        redisTemplate.opsForValue().set(token,userId,3600, TimeUnit.SECONDS);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 拦截器后置处理，可在这里设置响应头等
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 拦截器完成处理，可在这里进行资源清理等
    }
}